<?php
namespace Admin\Controller;
use DOMDocument;
use Think\Exception;
use XMLReader;

/**
 * 业务相关控制器
 * Class BusinessController
 * @package Admin\Controller
 */
class BusinessController extends AbstractController {
    /**
     * 业务列表
     */
    public function index(){
        /*
        $keyword = I('keyword');
        if(!empty($keyword)){
            $where['Name'] = array('like','%'.$keyword.'%');
        }
        $where['IsDel'] = array('neq','1');

        $count = M('Business')->where($where)->count();
        $page = $this->page($count, 10);
        $list = M('Business')->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();
        $this->assign('list',$list);
        $this->assign("page", $page->show('Admin'));
        */

        $this->auth_url_model = D("Business");
        //$AuthRules = $this->auth_url_model->select();
        $result = $this->auth_url_model->select();
        $tree = new \Think\Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $AuthRules=array();
        foreach ($result as $A){
            $AuthRules[$A['ID']]=$A;
        }
        foreach ($result as $n=> $r) {
            $result[$n]['Key'] = $n + 1;
            $result[$n]['ParentID_node'] = ($r['ParentID']) ? ' class="child-of-node-' . $r['ParentID'] . '"' : '';
            $result[$n]['style'] = empty($r['ParentID']) ? '' : 'display:none;';
            $result[$n]['str_manage'] = '';
            if(true){
                $result[$n]['str_manage'] .= '<a href="' . U("Admin/Business/setting", array("id" => $r['ID'])) . '">配置</a>';
            }
            if(true){
                if(strlen($result[$n]['str_manage']) > 0){
                    $result[$n]['str_manage'] .= ' | ';
                }
                $result[$n]['str_manage'] .= '<a href="' . U("Admin/Business/edit", array("id" => $r['ID'])) . '">编辑</a>';
            }
            if(true){
                if(strlen($result[$n]['str_manage']) > 0){
                    $result[$n]['str_manage'] .= ' | ';
                }
                $result[$n]['str_manage'] .=  '<a class="js-ajax-delete" href="' . U("Admin/Business/delete", array("id" => $r['ID']) ). '">删除</a>';
            }
            //$result[$n]['str_manage'] = '<a href="' . U("Auth/add", array("ParentID" => $r['ID'], "arid" => I("get.arid"))) . '">添加子权限</a> | <a href="' . U("Auth/edit", array("id" => $r['ID'],"arid" => I("get.arid"))) . '">编辑</a> | <a class="js-ajax-delete" href="' . U("Auth/delete", array("id" => $r['ID'], "arid" => I("get.arid")) ). '">删除</a> ';
        }

        $tree->init($result);
        $str = "<tr id='node-\$ID' \$ParentID_node style='\$style'>
                    <td style='padding-left:20px;' class='expander'></td>
                    <td>\$Key</td>
                    <td>\$Name</td>
                    <td>\$spacer\$Name:\$Memo</td>
                    <td>\$CreateTime</td>
                    <td>\$str_manage</td>
                </tr>";

        $categorys = $tree->get_tree(0, $str);
        $this->assign("categorys", $categorys);
        $this->display();
    }

    /**
     * 添加业务
     */
    public function add(){
        if(IS_POST){
            $data = $_POST;
            $data['CreateTime'] = date('Y-m-d H:i:s');
            $data['UpdateTime'] = $data['CreateTime'];
            $data['CreateUserID'] = session('USER_ID');

            try{
                $result = M('Business')->add($data);

                if($result){
                    if($data['attachList'] && strlen($data['attachList']) > 4){
                        //{{"Name":"sadfa","Memo":"sdf"}{"Name":"sadf","Memo":"asdf"}{"Name":"dsaf","Memo":"asfd"}}
                        $list = json_decode($data['attachList']);
                        $list = preg_split('/}{/',$list);
                        foreach($list as $attach){
                            $attach = preg_replace('/[{|}]/','',$attach);
                            $attach = preg_replace('/\"\"/','"',$attach);
                            $attach = preg_split('/,/',$attach);
                            list($labelName,$labelValue) = preg_split('/:/',$attach[0]);
                            list($label2Name,$label2Value) = preg_split('/:/',$attach[1]);
                            $fileData['Name'] = preg_replace('/"/','',stripslashes($labelValue));
                            $fileData['Memo'] = preg_replace('/"/','',stripslashes($label2Value));
                            $fileData['BusiID'] = $result;
                            //todo:插入数据表
                            M('Business_attachment_list')->add($fileData);
                        }
                    }
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            } catch (Exception $exception){
                $this->error($exception->getMessage());
            }
        }else{
            $this->display();
        }
    }

    /**
     * 编辑业务
     */
    public function edit(){
        if(IS_POST){
            $data = $_POST;
            if(isset($data['ID'])){
                try{
                    $business = M('Business')->find($data['ID']);
                    if($data['ParentID']===$business['ID']){
                        throw new Exception('不能选择自身业务为父业务');
                    }
                    if(isset($data['Name'])){
                        $business['Name'] = $data['Name'];
                    }
                    if(isset($data['Memo'])){
                        $business['Memo'] = $data['Memo'];
                    }
                    if(isset($data['ParentID'])){
                        $business['ParentID'] = $data['ParentID'];
                    }
                    $business['UpdateTime'] = date('Y-m-d H:i:s');
                    $result = M('Business')->save($business);
                    if($data['attachList']){
                        //{{"Name":"sadfa","Memo":"sdf"}{"Name":"sadf","Memo":"asdf"}{"Name":"dsaf","Memo":"asfd"}}
                        $list = json_decode($data['attachList']);
                        $list = preg_split('/}{/',$list);
                        foreach($list as $attach){
                            $attach = preg_replace('/[{|}]/','',$attach);
                            $attach = preg_replace('/\"\"/','"',$attach);
                            if(!$attach){continue;}
                            $attach = preg_split('/,/',$attach);
                            list($labelName,$labelValue) = preg_split('/:/',$attach[0]);
                            list($label2Name,$label2Value) = preg_split('/:/',$attach[1]);
                            $fileData['Name'] = preg_replace('/"/','',stripslashes($labelValue));
                            $fileData['Memo'] = preg_replace('/"/','',stripslashes($label2Value));
                            $fileData['BusiID'] = $data['ID'];
                            //todo:插入数据表
                            M('Business_attachment_list')->add($fileData);
                        }
                    }
                    $this->success('编辑成功');

                } catch (Exception $exception){
                    $this->error($exception->getMessage());
                }
            }else{
                $this->error('参数错误');
            }
        }else{
            $id = I('id',0,'intval');
            $business = M('Business as b')->join('left join Business as pb on pb.ID=b.ParentID')
                ->join('left join user as u on u.ID=b.UserID')
                ->join('left join department as d on d.ID=b.DepID')
                ->where(array('b.ID' => $id))->field('b.*,pb.Name as ParentName,u.TrueName as UserName,d.Name as DepName')->find();
            $attachList = M('business_attachment_list')->where(array('BusiID' => $id,'IsDel' => 0))->select();
            $this->assign('business',$business);
            $this->assign('attachList',$attachList);
            $this->display();
        }
    }

    /**
     * 删除附件
     */
    public function deleteFile(){
        $id = I('id',0,'intval');
        $file = M('Business_attachment_list')->where(array('ID' => $id))->find();
        if($file){
            $file['IsDel'] = 1;
            M('Business_attachment_list')->save($file);
            //修改任务表的更新时间
            $business = M('Business')->where(array('ID' => $file['BusiID']))->find();
            $business['UpdateTime'] = date('Y-m-d H:i:s');
            M('Business')->save($business);
            $this->success('删除成功');
        }else{
            $this->error('删除失败，参数错误');
        }
    }

    /**
     * 删除业务
     */
    public function delete(){
        $id = I('id',0,'intval');
        $where['BusiID'] = $id;
        $count = M('Businessprocess')->where($where)->count();
        if($count){
            $this->error('该业务已配置流程，不能删除');
        }else{
            $business = M('Business')->find($id);
            if($business){
                $pcount = M('Business')->where(array('ParentID' => $id))->count();
                if($pcount){
                    $this->error('该业务还有子业务，不能删除');return;
                }
                $business['IsDel'] = 1;
                $result = M('Business')->save($business);
                if($result){
                    $this->success('删除成功');
                }else{
                    $this->success('删除失败');
                }
            }else{
                $this->error('删除失败，参数错误');
            }
        }
    }

    /**
     * 配置业务流程
     */
    public function setting(){
        $businessTempFile = null;
        $filePath = './data/business/business.php';
        if(file_exists($filePath)){
            $businessTempFile = require ($filePath);
        }

        $list = null;
        $id = I('id');
        $business = M('Business')->find($id);
        $where['b.BusiID'] = $id;
        $where['b.IsDel'] = array('neq','1');
        $result = M('Businessprocess as b')->join('left join (select bb.PrevBPID,GROUP_CONCAT(bb.ID) as Children from businessprocess as bb where bb.IsDel <> 1 GROUP BY bb.PrevBPID) as bu on bu.PrevBPID=b.ID')
            ->where($where)->select();

        if($result){
            foreach($result as $key=>$process){
                $line['id'] = $process['ID'];
                $line['flow_id'] = $process['BusiID'];
                $line['process_name'] = $process['Name'];
                $line['process_to'] = $process['Children'] ? $process['Children'] : 0;
                $line['icon'] = 'icon-play';
                $line['style'] = '';

                if(isset($businessTempFile[$id][$process['ID']])){
                    $line['style'] = $businessTempFile[$id][$process['ID']]['style'];
                }

                $list [$process['ID']] = $line;
            }

        }

        $this->assign('total',count($result));
        $this->assign('processData',json_encode($list));
        $this->assign('business',$business);
        $this->display();
    }

    public function selector(){
        $pid = I('id',0,'intval');
        $where['ParentID'] = $pid;
        if($pid === 0){
            $where['ParentID']  = array(array('exp','is null'), array('eq','0'),'or');
        }
        $result = M('Business')->where($where)->select();
        $jsonStr = '[';
        foreach($result as $business){
            $children = M('Business')->where(array('ParentID' => $business['ID']))->count();
            $isParent = $children ? 'true' : 'false';
            $jsonStr .= "{ id:'".$business['ID']."',name:'".$business['Name']."',isParent:".$isParent."}";
            $jsonStr .= ',';
        }
        $jsonStr = substr($jsonStr,0,strlen($jsonStr) -1);
        $jsonStr .= ']';

        echo $jsonStr;
    }

    public function search(){
        $keyword = I('keyword');
        $where['IsDel'] = 0;
        $where['Name'] = array('like','%'.$keyword.'%');
        $result = M('Business')->where($where)->select();
        $jsonStr = '[';
        $jsonArray = [];
        foreach($result as $business){
            $children = M('Business')->where(array('ParentID' => $business['ID']))->count();
            $isParent = $children ? 'true' : 'false';
            $jsonStr .= "{ id:'".$business['ID']."',name:'".$business['Name']."',isParent:".$isParent."}";
            $jsonStr .= ',';
            $line = "{ id:'".$business['ID']."',name:'".$business['Name']."',isParent:".$isParent."}";
            $jsonArray[] = $business;
        }
        if(strlen($jsonStr) > 1){
            $jsonStr = substr($jsonStr,0,strlen($jsonStr) -1);
        }
        $jsonStr .= ']';

        echo json_encode($jsonArray);
    }
}